from flask import Blueprint, request, jsonify
import json
from utils.db import db1
from view.compan import get_data
from utils.redison import r

bp_work = Blueprint('work', __name__)

import json


@bp_work.route('/work', methods=['PUT', 'GET'])
def work():
    if request.method == 'PUT':
        data = get_data()
        list = json.loads(data["list"])
        print(list)
        sql = 'update yewu set params = "%s" where id = %d' % (list, int(data['id']))
        db1.update(sql)
        return jsonify({'code': 200})
    elif request.method == 'GET':
        id = request.args.get('id')
        if not id:
            sql = 'select * from yewu'
            res = db1.findall(sql)
            return jsonify({'code': 200, 'list': res})
        else:
            sql = 'select * from yewu where id = %d' % (int(id))
            res = db1.findone(sql)
            return jsonify({'code': 200, "list": res})


@bp_work.route('/source', methods=['GET'])
def source():
    if request.method == 'GET':
        value = r.get_str('datasource')
        if value:
            list = eval(value)
        else:
            sql = 'select * from tablename'
            res = db1.findall(sql)
            list = []
            if res:
                for i in res:
                    dict = {"id": i["id"], "name": i["name"]}
                    sql1 = 'select id,name,type from %s' % (i["tablen"])
                    res1 = db1.findall(sql1)
                    dict['son'] = res1
                    list.append(dict)
            r.set_str('datasource', json.dumps(list))
        return jsonify({"code": 200, 'list': list})


@bp_work.route('/holiday', methods=['GET'])
def holiday():
    if request.method == 'GET':
        id = int(request.args.get('id'))
        sql = 'select * from yewu where id = %d' % (id)
        res = db1.findone(sql)
        return jsonify({'code': 200, 'list': res})
